/* RMORPG - Logger.cpp
   Copyright (C) 2006, Michael Borgmann <code@lechuck.de>
   This Code is released under the new BSD license
*/

#include <iostream>
#include "Logger.h"

using namespace rmorpg;

// Title of log
std::string Logger::Title(const std::string &title) {
	return "========================================================\n" +
		title + "\n" +
		"========================================================\n";
}

// Time Stamp - Www Mmm dd hh:mm:ss yyyy
std::string Logger::TimeStamp() {
	char time_stamp[28];
	time_t now = time(NULL);
	struct tm *fetched_time = gmtime(&now);
	strftime(time_stamp, 28, "[%a %b %e %H:%M:%S %Y] ", fetched_time);
	return time_stamp;
}

// Default Constructor
Logger::Logger(const std::string &filename, const std::string &title) {
	// open file to check existence
	logfile.open(filename.c_str(), std::ios::in);

	// file exist
	if (logfile.is_open()) {
		logfile.close();
		logfile.open(filename.c_str(), std::ios::out | std::ios::app);
	}
	else {
		logfile.close();
		logfile.open(filename.c_str(), std::ios::out);
		logfile << Title(title);
	}

	time_t now = time(NULL);
	logfile << "\n" << TimeStamp() << "Session opened.\n";
}

// Default Destructor
Logger::~Logger() {
	logfile << TimeStamp() << "Session closed.\n";
	logfile.close();
}

// Write a message into the log file
void Logger::Log(const std::string &message) {
	logfile << TimeStamp() << message << std::endl;
}
